//
//  LSReadTestView.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/10/31.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSReadTestView.h"
#import "KZTimeCountDownView.h"
#import "KZEvaluateResultView.h"
#import "KYTestConfig.h"
#import "KYTestEngine.h"
#import "KZSoundTool.h"
#import "XYVoiceConverter.h"

@implementation LSReadTestView {
    BOOL                        _isCheck;//是否是查看界面
    BOOL                        _isPlaying;//是否是正在播放
    BOOL                        _isPlayEnd;//是否播放结束
    NSTimer                     *_timer;
    CGFloat                     _second;
    BKAudioPlayer               *_player;
    CGFloat                     _playRate;
    CGFloat                     _readRate;
    NSInteger                   _count;//进行到第几步的计数
    NSInteger                   _recordTotalTime;
    NSString                    *_content;//测试文本
    BOOL                        _isSep;
    NSString                    *_pWavPath; //整段录音存储路径
    //1.预读
    UIView                      *_status1View;
    KZTimeCountDownView         *_waitTimeView; // 预读倒计时
    
    //2.录音
    UIView                      *_status2View;
    KZTimeCountDownView         *_recordView;
    
    //3.评测中
    UIView                      *_status3View;
    UIImageView                 *_evaluatingView;
    
    //4.评测合格，
    UIView                      *_status4View;
    KZEvaluateResultView        *_successView;
    
    //5. 不合格，再次朗读
    UIView                      *_status5View;
    KZEvaluateResultView        *_failureView;
    
    //6.重新作答
    UIView                      *_status6View;
    UIButton                    *_repeatBtn;
    
    //7.下一题
    UIView                      *_status7View;
    UIButton                    *_nextBtn;
    
    //8.分句朗读
    UIView                      *_status8View;
    UIButton                    *_sepSenBtn;
    
    //9.我的录音
    UIView                      *_status9View;
    KZTurmpetView               *_myRecordBtn;
    //10.参考示范
    UIView                      *_status10View;
    KZTurmpetView               *_trueRecordBtn;
    
    //11.播放喇叭
    UIView                      *_statu11View;
    KZTimeCountDownView         *_voicePlayView;// 听力播放
}

- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = YES;
       // _isReAnswer = YES;
        _isPlayEnd = YES;
        _isPlaying = NO;
    }
    
    return self;
}

- (void)setModel:(LSModelQues *)model {
    _model = model;
    _count = 0;
    if (self.speedLayer==1) {
        _playRate = 0.8;
        _readRate = LS_System.lowSpeed;
    } else if (self.speedLayer==2) {
        _playRate = 1.0;
        _readRate = LS_System.normalSpeed;
        
    } else if (self.speedLayer==3) {
        _playRate = 1.2;
        _readRate = LS_System.highSpeed;
    }
    
    //根据文本计算录音总时长
    _content = self.model.ChildList.firstObject.ChildAnswer;
    if (_content==nil || [_content isEqualToString:@""]) {
        _content = self.model.QuesBody ;
    }
    _recordTotalTime =  (NSInteger)([_content componentsSeparatedByString:@" "].count / _readRate);
    NSLog(@"_recordTotalTime=%ld",_recordTotalTime);
    [self setupUI];
}

- (void)setupUI {
    
    _player = [[BKAudioPlayer alloc] init];
    _player.delegateM = self;
    
    [self setupStatus1View];
    
    [self setupStatus2View];
    
    [self setupStatus3View];
    
    [self setupStatus4View];
    
    [self setupStatus5View];
    
    [self setupStatus6View];
    
    [self setupStatus7View];
    
    [self setupStatus8View];
    
    [self setupStatus9View];
    
    [self setupStatus10View];
    
    [self setupStatus11View];
}

- (void)setupStatus1View {
    
    _status1View = [UIView new];
    _status1View.userInteractionEnabled = YES;
    [self addSubview:_status1View];
    _status1View.alpha = 0;
    [_status1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _waitTimeView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypeWait withTime:_model.ReadTime+_model.WaitTime];
    [_status1View addSubview:_waitTimeView];
    [_waitTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_status1View);
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jumpToNext)];
    [_waitTimeView addGestureRecognizer:tap];
}

- (void)setupStatus2View {
    
    _status2View = [UIView new];
    _status2View.userInteractionEnabled = YES;
    [self addSubview:_status2View];
    _status2View.alpha = 0;
    [_status2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _recordView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypeRecordingFirst withTime:_recordTotalTime+2];
    [_status2View addSubview:_recordView];
    [_recordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_status2View);
    }];
}

- (void)setupStatus3View {
    
    _status3View = [UIView new];
    _status3View.userInteractionEnabled = YES;
    [self addSubview:_status3View];
    _status3View.alpha = 0;
    [_status3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _evaluatingView = [UIImageView new];
    [_evaluatingView gif:@"__4"];
    [_status3View addSubview:_evaluatingView];
    [_evaluatingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_status3View);
    }];
}

- (void)setupStatus4View {
    
    _status4View = [UIView new];
    _status4View.userInteractionEnabled = YES;
    [self addSubview:_status4View];
    _status4View.alpha = 0;
    [_status4View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _successView = [[KZEvaluateResultView alloc] initWithStatus:true];;
    [_status4View addSubview:_successView];
    [_successView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_status4View);
    }];
}

- (void)setupStatus5View {
    
    _status5View = [UIView new];
    _status5View.userInteractionEnabled = YES;
    [self addSubview:_status5View];
    _status5View.alpha = 0;
    [_status5View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _failureView = [[KZEvaluateResultView alloc] initWithStatus:false];;
    [_status5View addSubview:_failureView];
    [_failureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_status5View);
    }];
}

- (void)setupStatus6View {
    _status6View = [UIView new];
    _status6View.alpha = 0;
    [self.superview addSubview:_status6View];
    [_status6View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.superview).offset(W(46));
        make.width.height.mas_equalTo(W(64));
        make.centerY.equalTo(self);
    }];
    
    _repeatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _repeatBtn.layer.cornerRadius = W(32);
    _repeatBtn.layer.masksToBounds = true;
    _repeatBtn.layer.borderColor = KZThemeColor2.CGColor;
    _repeatBtn.layer.borderWidth = 1;
    _repeatBtn.backgroundColor = [UIColor whiteColor];
    [_repeatBtn setImage:[UIImage imageNamed:@"kz-重复"] forState:UIControlStateNormal];
    [_status6View addSubview:_repeatBtn];
    [_repeatBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status6View);
    }];
    [_repeatBtn addTarget:self action:@selector(reAnswer:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *shadowView2 = [UIView new];
    shadowView2.backgroundColor = UIColor.whiteColor;
    shadowView2.layer.cornerRadius = W(32);
    [_status6View insertSubview:shadowView2 belowSubview:_repeatBtn];
    [shadowView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_repeatBtn);
    }];
    shadowView2.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView2.layer.shadowRadius = 5;
    shadowView2.layer.shadowOpacity = 0.6;
    shadowView2.layer.shadowColor = KZThemeColor2.CGColor;
}

- (void)setupStatus7View {
    _status7View = [UIView new];
    _status7View.alpha = 0;
    [self.superview addSubview:_status7View];
    [_status7View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.superview).offset(-W(46));
        make.width.height.mas_equalTo(W(64));
        make.centerY.equalTo(self);
    }];
    
    UIView *nextView = [UIView new];
    [_status7View addSubview:nextView];
    [nextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status7View);
    }];
    nextView.layer.cornerRadius = W(32);
    nextView.layer.masksToBounds = true;
    // 渐变图层
    CAGradientLayer *gradientLayer2 = [CAGradientLayer layer];
    gradientLayer2.bounds = CGRectMake(0, 0, W(64), W(64));
    gradientLayer2.position = CGPointMake(W(32), W(32));
    gradientLayer2.colors = @[
                              (__bridge id)kzRGBA(11, 175, 251, 1).CGColor,
                              (__bridge id)kzRGBA(71, 204, 255, 1).CGColor,
                              ];
    [nextView.layer insertSublayer:gradientLayer2 atIndex:0];
    
    UIView *shadowView = [UIView new];
    shadowView.backgroundColor = UIColor.whiteColor;
    shadowView.layer.cornerRadius = W(32);
    [_status7View insertSubview:shadowView belowSubview:nextView];
    [shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(nextView);
    }];
    shadowView.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView.layer.shadowRadius = 5;
    shadowView.layer.shadowOpacity = 0.6;
    shadowView.layer.shadowColor = kzRGBA(11, 175, 251, 1).CGColor;
    
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nextBtn setImage:[UIImage imageNamed:@"kz-下一个"] forState:UIControlStateNormal];
    
    [_nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [nextView addSubview:_nextBtn];
    [_nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(nextView);
    }];
}

- (void)setupStatus8View {
    
    _status8View = [UIView new];
    _status8View.userInteractionEnabled = YES;
    [self addSubview:_status8View];
    _status8View.alpha = 0;
    [_status8View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _sepSenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_sepSenBtn setBackgroundImage:[UIImage imageNamed:@"LS-分句朗读"] forState:UIControlStateNormal];
    [_status8View addSubview:_sepSenBtn];
    [_sepSenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(95));
        make.center.equalTo(_status8View);
    }];
    [_sepSenBtn addTarget:self action:@selector(sepSenAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setupStatus9View {
    _status9View = [UIView new];
    _status9View.alpha = 0;
    [self.superview addSubview:_status9View];
    [_status9View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.superview).offset(W(46));
        make.height.mas_equalTo(W(30));
        make.width.mas_equalTo(W(100));
        make.bottom.equalTo(self.mas_top).offset(20);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    [_status9View addSubview:label];
    label.textColor = [UIColor colorWithHex:0x464646];
    label.font = FONT(W(11));
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_status9View);
        make.centerY.equalTo(_status9View);
        make.width.mas_equalTo(W(46));
        make.height.mas_equalTo(W(13));
    }];
    label.text = @"我的录音";
    
    _myRecordBtn = [[KZTurmpetView alloc] initWithTurmpetImage:[UIImage imageNamed:@"LS-喇叭2"] Color:[UIColor colorWithHex:0x3bcbf4]];
    [_status9View addSubview:_myRecordBtn];
    [_myRecordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label.mas_right);
        make.centerY.equalTo(_status9View);
        make.width.height.mas_equalTo(W(25));
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myRecordAction:)];
    [_status9View addGestureRecognizer:tap];
    
}

- (void)setupStatus10View {
    _status10View = [UIView new];
    _status10View.alpha = 0;
    [self.superview addSubview:_status10View];
    [_status10View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.superview).offset(W(-36));
        make.height.mas_equalTo(W(30));
        make.width.mas_equalTo(W(100));
        make.bottom.equalTo(self.mas_top).offset(20);
    }];
    
    _trueRecordBtn = [[KZTurmpetView alloc] initWithTurmpetImage:[UIImage imageNamed:@"LS-喇叭1"] Color:[UIColor colorWithHex:0x20bb5a]];
    [_status10View addSubview:_trueRecordBtn];
    [_trueRecordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_status10View);
        make.centerY.equalTo(_status10View);
        make.width.height.mas_equalTo(W(25));
    }];
    
    UILabel *label = [[UILabel alloc] init];
    [_status10View addSubview:label];
    label.textColor = [UIColor colorWithHex:0x464646];
    label.font = FONT(W(11));
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_trueRecordBtn.mas_left);
        make.centerY.equalTo(_status10View);
        make.width.mas_equalTo(W(46));
        make.height.mas_equalTo(W(13));
    }];
    label.text = @"参考示范";
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(trueRecordAction:)];
    [_status10View addGestureRecognizer:tap];
}

- (void)setupStatus11View  {
    
    _statu11View = [UIView new];
    _statu11View.userInteractionEnabled = YES;
    [self addSubview:_statu11View];
    _statu11View.alpha = 0;
    [_statu11View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _voicePlayView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypePlayVoice withTime:_model.TimeLong];
    [_statu11View addSubview:_voicePlayView];
    [_voicePlayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_statu11View);
    }];
    
}

- (void)jumpToNext {
    
    [_timer invalidate];
    _timer = nil;
    
    //预读消失
    [self addHideAnimation:_status1View];
    
    //录音出现
    [self addFadeAnimation:_status2View];
    
    //录音计时
    _second = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(time2Action:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    _count = 2;
    self.pauseType = LSQuesPauseType_Recording;
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
        [self.delegate LSReadTest:self PauseType:self.pauseType];
    }
    
    //调用评测系统
    [self startRecordTest];
}

#pragma mark - 交互操作
- (void)start {
    [self addFadeAnimation:_status1View];
    //开始预读
    _second = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(time1Action:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    _count = 1;
    self.pauseType = LSQuesPauseType_Waiting;
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
        [self.delegate LSReadTest:self PauseType:self.pauseType];
    }
}

- (void)reStartSpeedLayer:(NSInteger)speedLayer {
    
    if(_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    self.speedLayer = speedLayer;
    if (self.speedLayer==1) {
        _playRate = 0.8;
        _readRate = LS_System.lowSpeed;
    } else if (self.speedLayer==2) {
        _playRate = 1.0;
        _readRate = LS_System.normalSpeed;
        
    } else if (self.speedLayer==3) {
        _playRate = 1.2;
        _readRate = LS_System.highSpeed;
    }
    
    //需要隐藏全部的视图
    _status1View.alpha = 0;
    _status2View.alpha = 0;
    _status3View.alpha = 0;
    _status5View.alpha = 0;
    _status6View.alpha = 0;
    _status7View.alpha = 0;
    _status8View.alpha = 0;
    _status9View.alpha = 0;
    _status10View.alpha = 0;
    _statu11View.alpha = 0;
    [_player closePlayer];
    [[KYTestEngine sharedInstance] cancelEngine];
    
    //重新设置录音时间
    _recordTotalTime =  (NSInteger)([_content componentsSeparatedByString:@" "].count / _readRate);
    NSLog(@"_recordTotalTime=%ld",_recordTotalTime);
    _recordView.totalTime = _recordTotalTime+2;

    [self start];
    
    if (self.delegate &&[self.delegate respondsToSelector:@selector(LSReadReAnswer)])
    {
        [self.delegate LSReadReAnswer];
    }
    
}

- (void)startSecond
{
    [self addFadeAnimation:_status2View];
    
    //录音计时
    _second = 0;
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(time2Action:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    _count = 2;
    self.pauseType = LSQuesPauseType_Recording;
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
        [self.delegate LSReadTest:self PauseType:self.pauseType];
    }
    //调用评测系统
    [self startRecordTest];
}

- (void)time1Action:(id)sender {
    _second = _second+0.1;
    _waitTimeView.time = _second;
    if (_second >= _model.WaitTime+_model.ReadTime) {
        
        [_timer invalidate];
        _timer = nil;
        
        //预读消失
        [self addHideAnimation:_status1View];
        
        //录音出现
        [self addFadeAnimation:_status2View];
        
        //录音计时
        _second = 0;
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(time2Action:) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        _count = 2;
        self.pauseType = LSQuesPauseType_Recording;
        if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
            [self.delegate LSReadTest:self PauseType:self.pauseType];
        }
        //调用评测系统
        [self startRecordTest];
    }
}

- (void)time2Action:(id)sender {
    _second = _second+0.1;
    _recordView.totalTime = _recordTotalTime +2;
    _recordView.time = _second;
    
    if (_second >= _recordTotalTime+2) {
        
        [_timer invalidate];
        _timer = nil;
        
        //录音消失
        [self addHideAnimation:_status2View];
        
        //分析中...出现
        [self addFadeAnimation:_status3View];
        _count = 3;
        self.pauseType = LSQuesPauseType_Evaluating;
        if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
            [self.delegate LSReadTest:self PauseType:self.pauseType];
        }
        //结束评测，回调中返回结果
        [[KYTestEngine sharedInstance] stopEngine];
        
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:RecordingTime:TotalTime:)]) {
        [self.delegate LSReadTest:self RecordingTime:_second TotalTime:_recordTotalTime];
    }
    
}

//录音评测
- (void)startRecordTest {
    //配置评测参数
    KYTestConfig *config = [[KYTestConfig alloc] init];
    config.coreType = KYTestType_Paragraph;
    config.refText = _content;
    config.phonemeOption = KYPhonemeOption_KK;
    config.audioType = @"wav";
    config.sampleRate = 16000;
    config.sampleBytes = 2;
    config.soundIntensityEnable = YES;
    config.paragraph_need_word_score = YES;
    
    WeakObj(self);
    [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
        
        if([testResult rangeOfString:@"errId"].length > 0) {  //错误回调
            
            NSLog(@"result：%@",testResult);
            [MBProgressHUD showOnlyText:@"口语评测失败" position:KZHUDPositionModeCenter duration:3];
            
        } else if ([testResult rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
            NSError *error;
            NSData *rdata = [testResult dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
            CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
            NSLog(@"音量：%f",soundIntensity/10.0f);
             NSLog(@"_speedLayer：%ld",_speedLayer);
            _recordView.recordingView.percent = soundIntensity/10.0f;
            
        } else {
           
            NSString *wavPath = [KYTestEngine sharedInstance].currentWavPath;
            NSLog(@"wavPath=%@",wavPath);
            _pWavPath = wavPath;
            
            NSLog(@"%@",testResult);
            [selfWeak judgeResult:testResult];
           
        }
        
       
    }];
    
}

//判断最终结果
- (void)judgeResult:(NSString*)testResult {
    NSError *error;
    NSData *rdata = [testResult dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
    NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
    NSString *overall = [NSString stringWithFormat:@"%@",[jsonresult objectForKey:@"overall"]];
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
         
         //提交保存回调
         if(!_isReAnswer) {
             if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTestReslut:)]) {
                 [self.delegate LSReadTestReslut:resultDic];
             }
         }
         
         //分析消失
         [self addHideAnimation:_status3View];
         _count = 4;
         self.pauseType = LSQuesPauseType_End;
        if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
            [self.delegate LSReadTest:self PauseType:self.pauseType];
        }
        
        //正确/错误后的流程操作
         if(overall.integerValue>=LS_System.readScore) { //正确
             //音效正确
             //[KZSoundTool playSound:KZSoundType_correct];
             LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_correct];
             self.soundPlayer = player;
             
             if(!_isReAnswer) {//第一次就正确了
                 //显示正确
                 [self addFadeAnimation:_status4View];
                 
                 //自动进入下一题
                _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(time4Action:) userInfo:nil repeats:NO];
                [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                 
             } else { //显示重做，下一题，分句等按钮
                
                 [self addFadeAnimation:_status4View];
                 //[self showNextAndReAnswer];
                 _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(time5Action:) userInfo:_status4View repeats:NO];
                 [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                 
                 //调用知识点分析
                 [self getZSDResult:jsonresult];
             }
             
             
         } else {//错误
            //音效错误
            //[KZSoundTool playSound:KZSoundType_wrong];
             LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_wrong];
             self.soundPlayer = player;
             
             if(!_isReAnswer) {//第一次就错误了
                  self.isReAnswer = YES;
                 //显示错误
                 [self addFadeAnimation:_status5View];
                 //自动重新作答
                 _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(time3Action:) userInfo:nil repeats:NO];
                 [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                 
             } else { //显示重做，下一题，分句等按钮
                 
                 //显示错误
                 [self addFadeAnimation:_status5View];
                 //[self showNextAndReAnswer];
                 _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(time5Action:) userInfo:_status5View repeats:NO];
                 [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                 
                 //调用知识点分析
                 [self getZSDResult:jsonresult];
             }
             
             
         }
     });
    
}

- (void)getZSDResult:(NSDictionary*)jsonresult {
    NSString *testString = @"";
    NSArray *senarr = jsonresult[@"sentences"];
    for (NSInteger i = 0; i<senarr.count; i++) {
        NSDictionary *sen = senarr[i];
        NSArray *wordarr = sen[@"details"];
        for (NSInteger j = 0; j<wordarr.count; j++) {
            NSDictionary *word = wordarr[j];
            NSNumber *num = word[@"overall"];
            if (num.integerValue<LS_System.readScore) {
                //去除首尾标点
                NSMutableCharacterSet *set = [[NSMutableCharacterSet alloc] init];
                [set formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];//标点
                NSString *wordstring = [word[@"word"] stringByTrimmingCharactersInSet:set];
                testString = [NSString stringWithFormat:@"%@ %@",testString,wordstring];
            }
        }
    }
    
    NSLog(@"testString = %@",testString);
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadShowZSD:)]) {
        
        [self.delegate LSReadShowZSD:testString];
        
    }
    
}

 //自动重新作答
- (void)time3Action:(id)sender {
    
    [_timer invalidate];
    _timer = nil;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadReAnswer)]) {
        [self.delegate LSReadReAnswer];
    }
    
    [self addHideAnimation:_status5View];
    [self startSecond];
}

//自动下一题
- (void)time4Action:(id)sender {
    [_timer invalidate];
    _timer = nil;
    
    [self addHideAnimation:_status4View];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadNext)]) {
        [self.delegate LSReadNext];
    }
}

//隐藏正确/错误图标，显示下一题，重新作答按钮
- (void)time5Action:(NSTimer*)timer {
    
    UIView *view = timer.userInfo;
    [self addHideAnimation:view];
    
    [self showNextAndReAnswer];
    
    [_timer invalidate];
    _timer = nil;
    
    //错题时显示弹窗
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadShowWrongComplteView)]) {
        [self.delegate LSReadShowWrongComplteView];
    }
    
}

//显示重新作答，下一题
- (void)showNextAndReAnswer {
    [self addFadeAnimation:_status6View];
    [self addFadeAnimation:_status7View];
    [self addFadeAnimation:_status8View];
    [self addFadeAnimation:_status9View];
    [self addFadeAnimation:_status10View];
    [_myRecordBtn setPath];
    [_trueRecordBtn setPath];
}

#pragma mark - 分句朗读下的交互操作


#pragma mark - 动画
//显示动画
- (void)addFadeAnimation:(UIView*)view {
    
    CABasicAnimation * fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnim.fromValue = @(0);
    fadeAnim.toValue = @(1);
    fadeAnim.repeatCount = 1;
    fadeAnim.duration = 0.5;
    //以下两行同时设置才能保持移动后的位置状态不变
//    fadeAnim.fillMode=kCAFillModeForwards;
//    fadeAnim.removedOnCompletion = NO;
    [view.layer addAnimation:fadeAnim forKey:@"Fade"];
    view.alpha = 1;
}

//消失动画
- (void)addHideAnimation:(UIView*)view {
    
    CABasicAnimation * fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnim.fromValue = @(1);
    fadeAnim.toValue = @(0);
    fadeAnim.repeatCount = 1;
    fadeAnim.duration = 0.5;
    //以下两行同时设置才能保持移动后的位置状态不变
//    fadeAnim.fillMode=kCAFillModeForwards;
//    fadeAnim.removedOnCompletion = NO;
    [view.layer addAnimation:fadeAnim forKey:@"Hide"];
    view.alpha = 0;
}

#pragma mark - 按钮点击事件
- (void)reAnswer:(id)sender {
    
    [self cancelRecordPlay];
    
    [self addHideAnimation:_status6View];
    [self addHideAnimation:_status7View];
    [self addHideAnimation:_status8View];
    [self addHideAnimation:_status9View];
    [self addHideAnimation:_status10View];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadReAnswer)]) {
        [self.delegate LSReadReAnswer];
    }

    [self startSecond];
}

- (void)nextAction:(id)sender {
    
    [self cancelRecordPlay];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadNext)]) {
        [self.delegate LSReadNext];
    }
}

- (void)sepSenAction:(id)sender {
    _isSep = !_isSep;
    if (_isSep) {
        [_sepSenBtn setBackgroundImage:[UIImage imageNamed:@"LS-退出"] forState:UIControlStateNormal];
    } else {
        [_sepSenBtn setBackgroundImage:[UIImage imageNamed:@"LS-分句朗读"] forState:UIControlStateNormal];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadSepSenStauts:)]) {
        [self.delegate LSReadSepSenStauts:_isSep];
    }
    
    [self cancelRecordPlay];
}

- (void)myRecordAction:(id)sender {
    [_myRecordBtn play];
    [_trueRecordBtn stop];
    [_trueRecordBtn setPath];
    
    NSURL *url = [NSURL fileURLWithPath:_pWavPath];
    [_player playerUrl:url seekTotime:0 rateValue:1.0];
}

- (void)trueRecordAction:(id)sender {
    [_trueRecordBtn play];
    [_myRecordBtn stop];
    [_myRecordBtn setPath];
    
    NSURL *url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
    if (_playRate == 0) {
        _playRate = 1;
    }
    [_player playerUrl:url seekTotime:0 rateValue:_playRate];
}

//取消我的录音，参考示范播放
- (void)cancelRecordPlay {
    
    [_player playerPaused];
    [_player closePlayer];
    [_myRecordBtn stop];
    [_trueRecordBtn stop];
    [_myRecordBtn setPath];
    [_trueRecordBtn setPath];
}

#pragma mark - 分句评测操作流程
- (void)startSenTest:(NSString *)text {
    
    [self addHideAnimation:_status6View];
    [self addHideAnimation:_status7View];
    [self addHideAnimation:_status8View];
    [self addHideAnimation:_status9View];
    [self addHideAnimation:_status10View];
    
    [self addFadeAnimation:_status2View];
    
    //录音计时
    _second = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeSen1Action:) userInfo:text repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    _count = 2;
    self.pauseType = LSQuesPauseType_Recording;
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
        [self.delegate LSReadTest:self PauseType:self.pauseType];
    }
    //调用评测系统
    [self startSenRecordTest:text];
}

//录音评测
- (void)startSenRecordTest:(NSString*)text {
    //配置评测参数
    KYTestConfig *config = [[KYTestConfig alloc] init];
    config.coreType = KYTestType_Sentence;
    config.refText = text;
    config.phonemeOption = KYPhonemeOption_KK;
    config.audioType = @"wav";
    config.sampleRate = 16000;
    config.sampleBytes = 2;
    config.soundIntensityEnable = YES;
    config.paragraph_need_word_score = YES;
    
    WeakObj(self);
    [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
        
        if([testResult rangeOfString:@"errId"].length > 0) {  //错误回调
            
            NSLog(@"result：%@",testResult);
            [MBProgressHUD showOnlyText:@"口语评测失败" position:KZHUDPositionModeCenter duration:3];
            
        } else if ([testResult rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
            NSError *error;
            NSData *rdata = [testResult dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
            CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
            NSLog(@"音量：%f",soundIntensity/10.0f);
            NSLog(@"_speedLayer：%ld",_speedLayer);
            _recordView.recordingView.percent = soundIntensity/10.0f;
            
        } else {
            
//            NSString *wavPath = [KYTestEngine sharedInstance].currentWavPath;
//            NSLog(@"wavPath=%@",wavPath);
//            _pWavPath = wavPath;
            
            NSLog(@"%@",testResult);
            [selfWeak judgeSenResult:testResult];
            
            //分句音频合成
           // [self senAudioMergeSenResult:testResult SenText:text];
        }
        
        
    }];
    
}

- (void)judgeSenResult:(NSString*)testResult {
    NSError *error;
    NSData *rdata = [testResult dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
    NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
    NSString *overall = [NSString stringWithFormat:@"%@",[jsonresult objectForKey:@"overall"]];
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //分析消失
        [self addHideAnimation:_status3View];
        _count = 4;
        self.pauseType = LSQuesPauseType_End;
        if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
            [self.delegate LSReadTest:self PauseType:self.pauseType];
        }
        
        //正确/错误后的流程操作
        if(overall.integerValue>=LS_System.readScore) { //正确
            //音效正确
            //[KZSoundTool playSound:KZSoundType_correct];
            LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_correct];
            self.soundPlayer = player;
            
             [self addFadeAnimation:_status4View];
            
            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeSenAction:) userInfo:_status4View repeats:NO];
            [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
            
        } else {//错误
            //音效错误
            //[KZSoundTool playSound:KZSoundType_wrong];
            LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_wrong];
            self.soundPlayer = player;
            
            [self addFadeAnimation:_status5View];
            
            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeSenAction:) userInfo:_status5View repeats:NO];
            [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

        }
    });
    
}

#pragma mark - 分句音频合成
- (void)senAudioMergeSenResult:(NSString*)senResult SenText:(NSString*)sentext{
    NSInteger insertStartTime = 0;
    NSInteger insertEndTime = 0;
    NSError *error;
    NSData *rdata = [senResult dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
    NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
    NSArray *senInfoArr = jsonresult[@"sentences"];
    NSMutableArray *thisSeninfoArr = [NSMutableArray array];
    for (NSInteger i = 0; i<senInfoArr.count; i++) {
        NSDictionary *dict = senInfoArr[i];
        NSString *string = dict[@"sentence"];
        if ([sentext containsString:string]) {
            [thisSeninfoArr addObject:dict];
        }
    }
    
    //开始时间
    NSDictionary *startDict = thisSeninfoArr.firstObject;
    insertStartTime = ((NSNumber*)startDict[@"start"]).integerValue;
    if (insertStartTime==0) {
        NSRange range = [sentext rangeOfString:[sentext componentsSeparatedByString:@"."].firstObject];
        NSArray *array = [_content componentsSeparatedByString:[sentext substringFromIndex:range.length+range.location+1]];
        insertStartTime = [array.firstObject componentsSeparatedByString:@" "].count / _readRate;
    }
    
    //结束时间
    NSDictionary *endDict = thisSeninfoArr.lastObject;
    insertEndTime = ((NSNumber*)endDict[@"end"]).integerValue;
    if (insertEndTime==0) {
        NSRange range = [sentext rangeOfString:[sentext componentsSeparatedByString:@"."].firstObject];
        NSArray *array = [_content componentsSeparatedByString:[sentext substringFromIndex:range.length+range.location+1]];
        NSInteger startTime = [array.firstObject componentsSeparatedByString:@" "].count / _readRate;
        insertEndTime = startTime + [sentext componentsSeparatedByString:@" "].count / _readRate;
    }
    NSLog(@"insertStartTime = %ld,insertEndTime = %ld",insertStartTime,insertEndTime);
    
    [[XYVoiceConverter alloc] xyConvert_audioCropOriginalPath:_pWavPath insertPath:[KYTestEngine sharedInstance].currentWavPath insertStartTime:insertStartTime insertEndTime:insertEndTime saveID:@"111" isNeedMerge:YES];
}

#pragma mark - 分句时间操作
- (void)timeSenAction:(NSTimer*)timer {
    UIView *view = timer.userInfo;
    [self addHideAnimation:view];
    
    [_timer invalidate];
    _timer = nil;
    
    [self addFadeAnimation:_status6View];
    [self addFadeAnimation:_status7View];
    [self addFadeAnimation:_status8View];
    [self addFadeAnimation:_status9View];
    [self addFadeAnimation:_status10View];
}

- (void)timeSen1Action:(NSTimer*)timer {
    
    NSString *text = timer.userInfo;
    CGFloat totalTime = [text componentsSeparatedByString:@" "].count / _readRate;
    
    _second = _second+0.1;
    _recordView.totalTime = totalTime+2;
    _recordView.time = _second;
    
    if (_second >= totalTime+2) {
        
        [_timer invalidate];
        _timer = nil;
        
        //录音消失
        [self addHideAnimation:_status2View];
        
        //分析中...出现
        [self addFadeAnimation:_status3View];
        _count = 3;
        self.pauseType = LSQuesPauseType_Evaluating;
        if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
            [self.delegate LSReadTest:self PauseType:self.pauseType];
        }
        
        //结束评测，回调中返回结果
        [[KYTestEngine sharedInstance] stopEngine];
        
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSSenReadTest:SenRecordingTime:SenTotalTime:)]) {
        [self.delegate LSSenReadTest:self SenRecordingTime:_second SenTotalTime:totalTime];
    }
}


#pragma mark - 定时器取消和暂停、重启
- (void)pause {
    
    [_timer setFireDate:[NSDate distantFuture]];
    
    [[KYTestEngine sharedInstance] pauseEngine];
    
    if (_player.player) {
        [_player playerPaused];
    }
}

- (void)resume {
    
    if (self.pauseType==LSQuesPauseType_Recording) {
        //录音下非分句
        if (!_isSep) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadReAnswer)]) {
                [self.delegate LSReadReAnswer];
            }
            
            [[KYTestEngine sharedInstance] cancelEngine];
            [self startSecond];
        } else {
           ////录音下分句时，分句恢复原状
            
            [[KYTestEngine sharedInstance] cancelEngine];
            [self addHideAnimation:_status2View];
            [self showNextAndReAnswer];
            
            self.pauseType = LSQuesPauseType_End;
            if (self.delegate && [self.delegate respondsToSelector:@selector(LSReadTest:PauseType:)]) {
                [self.delegate LSReadTest:self PauseType:self.pauseType];
            }
            
        }
        
    } else {
        
        [_timer setFireDate:[NSDate distantPast]];
        
        [[KYTestEngine sharedInstance] resumeEngine];
        
        if (_player.player) {
            [_player playerPlay];
        }
    }
    
  
}

- (void)stop {
    [_timer invalidate];
    _timer = nil;

    [_player closePlayer];
    
    [[KYTestEngine sharedInstance] cancelEngine];
//
//    //消失
//    if (_count==1) {
//        [self addHideAnimation:_status1View];
//    }
//    if (_count==2) {
//        [self addHideAnimation:_status2View];
//    }
//    if (_count==3) {
//        [self addHideAnimation:_status3View];
//    }
}

#pragma mark - BKAudioPlayerDelegate
- (void)audioPlayEnd {
    
    [_myRecordBtn stop];
    [_trueRecordBtn stop];
    [_myRecordBtn setPath];
    [_trueRecordBtn setPath];
    
    _isPlayEnd = YES;
    
    [_player closePlayer];
    //喇叭暂停
    [_voicePlayView.turmpetView stop];
    
    if(_isCheck)  {
        [_voicePlayView reset];
        return;
    }
}

- (void)audioUpdateWith:(float)time Totaltime:(float)totalTime {
    _voicePlayView.totalTime = totalTime;
    _voicePlayView.time = time;
    _isPlayEnd = NO;
}

- (void)showPlayerVoice {
    _statu11View.alpha = 1;
    [_voicePlayView.turmpetView pause];
    _isCheck = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playOrPause:)];
    [_statu11View addGestureRecognizer:tap];
   // [_voicePlayView.turmpetView setPath];
}

- (void)playOrPause:(id)sender {
    if (_isPlayEnd) {
        NSURL *url = nil;
        if ([_from isEqualToString:@"A00"]) {
            url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.model.AudioList.firstObject.AudioPath]];
        } else {
            
            url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
        }
        NSLog(@"url=%@",url);
        [_player playerUrl:url seekTotime:0 rateValue:_playRate];
        [_voicePlayView.turmpetView play];
        _isPlaying = YES;
        
    } else {
        
        if (_isPlaying) {
            [_player playerPaused];
            [_voicePlayView.turmpetView pause];
            _isPlaying = NO;
        } else {
            [_player playerPlay];
            [_voicePlayView.turmpetView resume];
            _isPlaying = YES;
        }
        
    }
}


@end
